// 管理 左侧4个  张
var express = require('express');
var router = express.Router();
const db = require('../../db/db');

// 牲畜列表信息
router.get('/cattleList', async function (req, res, next) {
    try {
        const result = await new Promise((resolve, reject) => {
            db.query("SELECT F_Id,F_IMEI FROM nc_livestock", function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
        res.send({ code: 200, msg: '成功', data: result });
    } catch (err) {
        res.send({ code: 0, msg: '服务器出错了，等会再试试罢' });
    }
});

// 牲畜详细信息
router.get('/cattleDetail', async function (req, res, next) {
    let F_Id = req.query.id;
    if (!F_Id) {
        return res.send({ code: 0, msg: '不给ID我也没法给你数据...' });
    }

    try {
        const cowinfoResult = await new Promise((resolve, reject) => {
            db.query("SELECT F_Type_Id,F_Sex,F_Birthday,F_Csweight,F_Weight,F_State,tzzb FROM nc_livestock WHERE F_Id = ?", F_Id, function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });

        if (cowinfoResult.length == 0) {
            return res.send({ code: 0, msg: '没有这个牲畜信息' });
        }

        const info = { cowinfo: cowinfoResult };

        const eartagResult = await new Promise((resolve, reject) => {
            db.query("SELECT F_IMEI,F_Quantity FROM nc_device_eartag WHERE F_LivestockId=?", F_Id, function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });

        info.eartag = eartagResult.length == 0 ? null : eartagResult;

        const necklaceResult = await new Promise((resolve, reject) => {
            db.query("SELECT F_IMEI,F_Quantity FROM nc_device_necklace WHERE F_LivestockId=?", F_Id, function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });

        info.necklace = necklaceResult.length == 0 ? null : necklaceResult;

        const typeResult = await new Promise((resolve, reject) => {
            db.query("SELECT F_Title FROM nc_livestock_type WHERE F_Id=?", info.cowinfo[0].F_Type_Id, function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });

        info.cowinfo[0].F_Type_Id = typeResult.length == 0 ? "未查询到品种信息" : typeResult[0].F_Title;
        info.cowinfo[0].type = '牛';

        let birthDate = new Date(info.cowinfo[0].F_Birthday);
        let currentDate = new Date();
        let age = currentDate.getFullYear() - birthDate.getFullYear();
        if (currentDate.getMonth() < birthDate.getMonth() || (currentDate.getMonth() == birthDate.getMonth() && currentDate.getDate() < birthDate.getDate())) {
            age--;
        }
        info.cowinfo[0].brithday = age + "岁" + (currentDate.getMonth() + 1) + "月";

        res.send({ code: 200, msg: '成功', data: info });
    } catch (err) {
        res.send({ code: 0, msg: '服务器出错了，等会再试试罢', data: err });
    }
});

// 检疫首页接口
router.get('/quarantine', async function (req, res, next) {
    try {
        const quarantineResult = await new Promise((resolve, reject) => {
            db.query("SELECT F_liveid,F_Stand,F_UserName,F_StTime,F_Title FROM nc_quarantine", function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });

        const cowResult = await new Promise((resolve, reject) => {
            db.query("SELECT F_Id,F_IMEI FROM nc_livestock", function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });

        const info = { quarantine: quarantineResult };

        info.quarantine.forEach(qitem => {
            const cowItem = cowResult.find(item => item.F_Id == qitem.F_liveid);
            if (cowItem) {
                qitem.F_IMEI = cowItem.F_IMEI;
            }
        });

        res.send({ code: 200, msg: '成功', data: info });
    } catch (err) {
        res.send({ code: 0, msg: '服务器出错了，等会再试试罢', data: err });
    }
});

// 新增检疫记录接口
router.post('/addQuarantine', async function (req, res, next) {
    let createTime = '2085-5-31 12:00:00';

    if (!req.body.F_liveid || !req.body.F_Stand || !req.body.F_UserName || !req.body.F_Title || !req.body.F_Phone || !req.body.F_StTime || !req.body.F_Address || !req.body.F_Level || !req.body.F_Remark || !req.body.F_ResultImage) {
        return res.send({ code: 0, msg: '请填写完整信息' });
    } else if (req.body.F_Level != 1 && req.body.F_Level != 2 && req.body.F_Level != 0) {
        return res.send({ code: 0, msg: '检疫结果的格式错误' });
    }

    try {
        const F_Id = generateRandomString(20);
        await new Promise((resolve, reject) => {
            db.query("INSERT INTO nc_quarantine(F_Id,F_liveid,F_Stand,F_UserName,F_Title,F_Phone,F_StTime,F_Address,F_Level,F_Remark,F_ResultImage,F_CreateTime) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)",
                [F_Id, req.body.F_liveid, req.body.F_Stand, req.body.F_UserName, req.body.F_Title, req.body.F_Phone, req.body.F_StTime, req.body.F_Address, req.body.F_Level, req.body.F_Remark, req.body.F_ResultImage, createTime],
                function (err, result) {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                });
        });

        res.send({ code: 200, msg: '添加成功', data: [F_Id, req.body.F_liveid, req.body.F_Stand, req.body.F_UserName, req.body.F_Title, req.body.F_Phone, req.body.F_StTime, req.body.F_Address, req.body.F_Level, req.body.F_Remark, req.body.F_ResultImage, createTime] });
    } catch (err) {
        res.send({ code: 0, msg: '服务器出错了，等会再试试罢', data: err });
    }
});

// 检疫信息接口
router.get('/quarantineInfo', async function (req, res, next) {
    try {
        const result = await new Promise((resolve, reject) => {
            db.query("SELECT F_Stand,F_UserName,F_StTime,F_Title,F_ResultImage FROM nc_quarantine where F_liveid = ?", req.query.id, function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
        res.send({ code: 200, msg: '成功', data: result });
    } catch (err) {
        res.send({ code: 0, msg: '服务器出错了，等会再试试罢', data: err });
    }
});

// 繁殖管理列表接口
router.get('/breedingList', async function (req, res, next) {
    try {
        const breedingResult = await new Promise((resolve, reject) => {
            db.query("select F_Title,F_liveid,F_EsTimateTime,F_SjTimateTime,F_Opert,F_CreateTime from nc_growth_log where F_Title = '发情'", function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });

        const neverbreedResult = await new Promise((resolve, reject) => {
            db.query("select F_Title,F_liveid,F_SjTimateTime,F_Opert,F_CreateTime from nc_growth_log where F_Title = '节育'", function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });

        const cowResult = await new Promise((resolve, reject) => {
            db.query("SELECT F_Id,F_IMEI FROM nc_livestock", function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });

        const info = {
            breedingList: breedingResult,
            neverbreedList: neverbreedResult
        };

        info.breedingList.forEach(item => {
            const cowItem = cowResult.find(Litem => Litem.F_Id == item.F_liveid);
            if (cowItem) {
                item.F_IMEI = cowItem.F_IMEI;
            }
        });

        info.neverbreedList.forEach(item => {
            const cowItem = cowResult.find(Litem => Litem.F_Id == item.F_liveid);
            if (cowItem) {
                item.F_IMEI = cowItem.F_IMEI;
            }
        });

        res.send({ code: 200, msg: '成功', data: info });
    } catch (err) {
        res.send({ code: 0, msg: '服务器出错了，等会再试试罢', data: err });
    }
});

// 繁殖管理新增发情信息接口
router.post('/addBreeding', async function (req, res, next) {
    let F_Id = generateRandomString(20);
    let createTime = '2085-5-31 12:00:00';

    try {
        await new Promise((resolve, reject) => {
            db.query("INSERT INTO nc_growth_log(F_Id,F_Title,F_liveid,F_EsTimateTime,F_SjTimateTime,F_Opert,F_CreateTime,F_Remark,F_Phone,F_Address) VALUES(?,?,?,?,?,?,?,?,?,?)",
                [F_Id, req.body.F_Title, req.body.F_liveid, req.body.F_EsTimateTime, req.body.F_SjTimateTime, req.body.F_Opert, createTime, req.body.F_Remark, req.body.F_Phone, req.body.F_Address], function (err, result) {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                });
        });

        res.send({ code: 200, msg: '添加成功', data: [F_Id, req.body.F_Title, req.body.F_liveid, req.body.F_EsTimateTime, req.body.F_SjTimateTime, req.body.F_Opert, createTime, req.body.F_Remark, req.body.F_Phone, req.body.F_Address] });
    } catch (err) {
        res.send({ code: 0, msg: '服务器出错了，等会再试试罢', data: err });
    }
});

// 繁殖管理新增节育信息接口
router.post('/addNerverBreed', async function (req, res, next) {
    let F_Id = generateRandomString(20);
    let createTime = '2085-5-31 12:00:00';
    req.body.F_EsTimateTime = req.body.F_SjTimateTime;
    req.body.F_Title = '节育';

    try {
        await new Promise((resolve, reject) => {
            db.query("INSERT INTO nc_growth_log(F_Id,F_Title,F_liveid,F_EsTimateTime,F_SjTimateTime,F_Opert,F_CreateTime,F_Remark,F_Phone,F_Address) VALUES(?,?,?,?,?,?,?,?,?,?)",
                [F_Id, req.body.F_Title, req.body.F_liveid, req.body.F_EsTimateTime, req.body.F_SjTimateTime, req.body.F_Opert, createTime, req.body.F_Remark, req.body.F_Phone, req.body.F_Address], function (err, result) {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                });
        });

        res.send({ code: 200, msg: '添加成功', data: [F_Id, req.body.F_Title, req.body.F_liveid, req.body.F_EsTimateTime, req.body.F_SjTimateTime, req.body.F_Opert, createTime, req.body.F_Remark, req.body.F_Phone, req.body.F_Address] });
    } catch (err) {
        res.send({ code: 0, msg: '服务器出错了，等会再试试罢', data: err });
    }
});

// 管理首页健康信息
router.get('/healthInfo', async function (req, res, next) {
    try {
        const result = await new Promise((resolve, reject) => {
            db.query("select F_JkState from nc_livestock", function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });

        const info = {
            countNum: result.length,
            healthNum: result.length,
            unHealthNum: 0
        };

        result.forEach(item => {
            if (item.F_JkState == 1) {
                info.healthNum--;
                info.unHealthNum++;
            }
        });

        res.send({ code: 200, msg: '成功', data: info });
    } catch (err) {
        res.send({ code: 0, msg: '服务器出错了，等会再试试罢', data: err });
    }
});

//溯源信息模块繁殖信息接口
router.get('/breedingInfo', async function (req, res, next) {
    let id = req.query.id;
    let error = false;
    let info = {};
    let Rdata = {};
    let jy = false;
    let IMEI = '';
    let man = '';

    try {
        // 牲畜信息获取
        const cowResult = await new Promise((resolve, reject) => {
            db.query("select F_Id,F_IMEI,F_Birthday,F_Jy,F_Csweight,F_Fathor,F_Mathor from nc_livestock", function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
        info.cowList = cowResult;

        // 配种信息获取
        const descentResult = await new Promise((resolve, reject) => {
            db.query("select F_PaternalLine,F_Matriarchal,F_ReproTime,F_UserName,F_Id from nc_descent", function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
        info.descentList = descentResult;

        // 发情、节育信息获取
        const growthResult = await new Promise((resolve, reject) => {
            db.query("select F_liveid,F_EsTimateTime,F_SjTimateTime,F_Opert from nc_growth_log", function (err, result) {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            });
        });
        info.growthList = growthResult;

        // 牲畜信息处理
        Rdata.brithDate = '未查询到该牲畜信息';
        info.cowList.forEach(item => {
            if (item.F_Id == id) {
                Rdata.brithDate = {};
                Rdata.brithDate.brithday = item.F_Birthday;
                Rdata.brithDate.Bweigth = item.F_Csweight;
                Rdata.brithDate.father = item.F_Fathor;
                Rdata.brithDate.mother = item.F_Mathor;
                Rdata.brithDate.man = man;
                IMEI = item.F_IMEI;
                jy = item.F_Jy;
            }
        });
        info.cowList.forEach(item => {
            if (item.F_Id == Rdata.brithDate.father) {
                Rdata.brithDate.father = item.F_IMEI;
            } else if (item.F_Id == Rdata.brithDate.mother) {
                Rdata.brithDate.mother = item.F_IMEI;
            }
        });

        // 发情信息处理
        Rdata.growthList = '无发情信息';
        info.growthList.forEach(item => {
            if (item.F_liveid == id) {
                Rdata.growthList = {};
                Rdata.growthList.F_EsTimateTime = item.F_EsTimateTime;
                Rdata.growthList.F_SjTimateTime = item.F_SjTimateTime;
                Rdata.growthList.F_Opert = item.F_Opert;
            }
        });

        // 配种信息处理
        Rdata.descentList = '无配种信息';
        info.descentList.forEach(item => {
            if (item.F_PaternalLine == id) {
                Rdata.descentList = {};
                Rdata.descentList.F_ReproTime = item.F_ReproTime;
                Rdata.descentList.F_UserName = item.F_UserName;
                Rdata.descentList.F_P = item.F_Matriarchal;
                man = item.F_UserName;
            } else if (item.F_Matriarchal == id) {
                Rdata.descentList = {};
                Rdata.descentList.F_ReproTime = item.F_ReproTime;
                Rdata.descentList.F_UserName = item.F_UserName;
                Rdata.descentList.F_P = item.F_PaternalLine;
                man = item.F_UserName;
            }
        });

        // 生育信息处理
        Rdata.birth = '无生育信息';
        info.cowList.forEach(item => {
            if (item.F_Mathor == id) {
                Rdata.birth = {};
                Rdata.birth.F_IMEI = item.F_IMEI;
                Rdata.birth.F_Birthday = item.F_Birthday;
                Rdata.birth.F_Man = man;
            }
        });

        // 节育信息处理
        if (jy) {
            Rdata.jyList = '无节育信息';
            info.growthList.forEach(item => {
                if (item.F_liveid == id) {
                    Rdata.jyList = {};
                    Rdata.jyList.F_SjTimateTime = item.F_SjTimateTime;
                    Rdata.jyList.F_Opert = item.F_Opert;
                }
            });
        }

        res.send({ code: 200, msg: '成功', data: Rdata });
    } catch (err) {
        error = true;
        res.send({ code: 0, msg: '服务器出错了，等会再试试罢', data: err });
    }
});


function generateRandomString(length) {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    const charactersLength = characters.length;

    for (let i = 0; i < length; i++) {
        const randomIndex = Math.floor(Math.random() * charactersLength);
        result += characters.charAt(randomIndex);
    }

    return result;
}

module.exports = router;